package com.lanou3g.ptp.achievement.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.lanou3g.ptp.achievement.mapper.ReportMapper;
import com.lanou3g.ptp.achievement.service.ReportService;
import com.lanou3g.ptp.entity.Message;
import com.lanou3g.ptp.entity.Report;
import com.lanou3g.ptp.entity.ReportSponsor;
import com.lanou3g.ptp.entity.Student;
import com.lanou3g.ptp.message.service.MessageService;
import com.lanou3g.ptp.student.service.StudentService;
import com.lanou3g.ptp.task.service.TaskService;
import com.lanou3g.ptp.taskstudent.service.TaskStudentService;
import com.lanou3g.ptp.utils.DateUtils;
import com.lanou3g.ptp.vo.AlertBody;
import com.lanou3g.ptp.vo.ReportVO;
import com.lanou3g.ptp.vo.TemplateData;
import com.lanou3g.ptp.vo.WxTmplMsg;
import com.lanou3g.ptp.wx.service.WxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 创建人: 武奇
 * 创建事件: 2019/8/29
 */
@Service(interfaceClass = ReportService.class, timeout = 5000)
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;

    @Reference
    private TaskStudentService taskStudentService;
    @Reference
    private StudentService studentService;
    @Reference
    private WxService wxService;
    @Reference
    private MessageService messageService;
    @Reference
    private TaskService taskService;

    @Override
    public List<ReportVO> findByTaskAndStudent(Long taskId, Long studentId) {
        return this.reportMapper.findByTaskIdAndStudentId(taskId, studentId);
    }

    @Override
    public Report findById(Long reportId) {
        return this.reportMapper.findById(reportId);
    }

    @Override
    public void excellentReport(Long id) {
        this.reportMapper.excellentReport(id);
    }

    @Override
    public boolean postReport(Report report) {
        Long taskId = report.getTaskId();
        if (report.getReportSponsorId() == null || taskId == null) {
            return false;
        }
        boolean studentInTask = taskStudentService.ifStudentInTask(report.getStudentId(), taskId);
        if (!studentInTask) {
            return false;
        }
        report.setExcellent(false);
        Date now = new Date();
        report.setCreateTime(now);
        report.setUpdateTime(now);
        report.setStatus(0);
        return reportMapper.insert(report) > 0;
    }

    @Override
    public List<ReportSponsor> findReportsToPost(Long studentId) {
        return reportMapper.findSponsorsByStudentId(studentId);
    }

    @Override
    public boolean alertReport(AlertBody alert) {

        Student student = this.studentService.findById(alert.getStudentId());
        Map<String, TemplateData> data = new HashMap<>();
        String content = "请提交阶段性报告！（已提交阶段性报告请忽略）";
        Date date = DateUtils.endTime(new Date());
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String s = df.format(date);
        data.put("keyword1", new TemplateData("阶段报告提交"));
        data.put("keyword2", new TemplateData(content));
        data.put("keyword3", new TemplateData(s));
        data.put("keyword4", new TemplateData("请尽快提交阶段性报告!"));

        boolean result = wxService.sendMessage(student.getOpenId(), WxTmplMsg.TYPE_REPORT, data);
        System.out.println(result);
        if (result) {
            Message message = new Message();
            message.setStudentId(student.getId());
            message.setTaskId(alert.getTaskId());
            message.setContent(content);
            boolean b = messageService.saveReportMessage(message);
            return b;
        }
        return false;

    }

    @Transactional
    @Override
    public boolean insertReportSponsor(Long taskId) {
        ReportSponsor reportSponsor = new ReportSponsor();
        Date date = new Date();
        reportSponsor.setTaskId(taskId);
        reportSponsor.setSponsorDate(date);
        reportSponsor.setCreateTime(date);
        reportSponsor.setUpdateTime(date);
        reportSponsor.setStatus(0);
        int i = reportMapper.insertReportSponsor(reportSponsor);
        if (i > 0) {
            String time = this.time();
            Map<String, TemplateData> data = new HashMap<>();
            String content = "提交近期的项目阶段性报告,时限截止到" + time;
            data.put("keyword1", new TemplateData("老师发起阶段性报告"));
            data.put("keyword2", new TemplateData(content));
            data.put("keyword3", new TemplateData(time));
            data.put("keyword4", new TemplateData("请尽快提交阶段性报告!"));

            List<Student> students = taskStudentService.findStudentsByTaskId(taskId);
            for (Student student : students) {
                String openId = student.getOpenId();
                if (openId != null && !openId.trim().equals("")) {
                    boolean result = wxService.sendMessage(openId, WxTmplMsg.TYPE_DIARY, data);
                    if (result) {
                        Message message = new Message();
                        message.setStudentId(student.getId());
                        message.setTaskId(taskId);
                        message.setContent(content);
                        messageService.saveReportMessage(message);
                    }
                }
            }
            return true;
        }
        return false;
    }

    @Override
    public List<ReportSponsor> findReportsToPostByTaskId(Long studentId, Long taskId) {
        return reportMapper.findSponsorsByStudentIdAndTaskId(studentId, taskId);
    }

    @Override
    public List<Report> findMyReportsByTaskId(Long studentId, Long taskId) {
        return reportMapper.findMyReportsByTaskId(studentId, taskId);
    }

    @Override
    public boolean putReport(Report report) {
        Date date = new Date();
        report.setUpdateTime(date);
        return reportMapper.putStudentReport(report);
    }

    private String time() {
        Date d = new Date();
        Calendar ca = Calendar.getInstance();
        ca.setTime(d);
        ca.add(Calendar.DATE, 3);// num为增加的天数，可以改变的
        d = ca.getTime();
        Date date = DateUtils.startTime(d);
        Date time = DateUtils.endTime(date);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currdate = format.format(time);
        return currdate;

    }

}
